package com.zhanlv.socketnet

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import com.zhanlv.socketnet.databinding.ActivityMainBinding
import org.json.JSONObject
import java.io.InputStream
import java.io.OutputStream
import java.net.Socket

class MainActivity : ComponentActivity(), SocketServer.ServerCallback, SocketClient.ClientCallback {

    private  val TAG = "MainActivity"
    private lateinit var binding: ActivityMainBinding

    //Socket服务是否打开
    private var openSocket = false

    private var connectSocket = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)


        binding.tvIpAddress.text = "Ip地址：${getIp()}"

        //开启服务/关闭服务 服务端处理
        binding.btnStartService.setOnClickListener {
            openSocket = if (openSocket) {
                SocketServer.stopServer();false
            } else SocketServer.startServer(this)

            //改变按钮文字
            binding.btnStartService.text = if (openSocket) "关闭服务" else "开启服务"
        }

        binding.btnConnectService.setOnClickListener {
            val ip = getIp()
            connectSocket = if (connectSocket) {
                SocketClient.closeConnect();false
            } else {
                SocketClient.connectServer(ip, this);true
            }

            binding.btnConnectService.text = if (connectSocket) "关闭连接" else "连接服务"
        }

        binding.btnClientSendMsg.setOnClickListener {
            //Log.i(TAG, "request " + System.currentTimeMillis())

            var jsonObject = JSONObject()
            jsonObject.put("androidId", "helloid123456")

            var jsonStr = jsonObject.toString()
            var payload = "${jsonStr.length}\n$jsonStr"

            /*var jsonObject = JSONObject()
            jsonObject.put("text", "helloid 123456")
            jsonObject.put("language", "zh-cn")
            jsonObject.put("voiceName", "zh-cn-XiaoxiaoMultilingualNeural")
            jsonObject.put("speechRate", 1)
            jsonObject.put("voiceStyle", "Newscast")
            jsonObject.put("quality", 1)

            var jsonStr = jsonObject.toString()
            var payload = "${jsonStr.length}\n$jsonStr"*/

            SocketClient.sendToServer(payload)
        }


        binding.btnServerSendMsg.setOnClickListener {
            SocketServer.sendToClient("服务端发送消息 给你mp3、音素和时间戳")
        }

        binding.btnTest.setOnClickListener{
            var intent = Intent(this, DHActivity::class.java)
            startActivity(intent)
        }

        binding.btnConnect.setOnClickListener {
            Log.i("wooran", "on connect")
            Thread(Runnable {
                remoteSocket = Socket("139.196.17.31", 6667)
                outputStream = remoteSocket.getOutputStream()
                inputStream = remoteSocket.getInputStream()
            }).start();
        }

        binding.btnResponse.setOnClickListener {
            Log.i("wooran", "on response")
            Thread(Runnable {
                while (true){
                    Thread.sleep(5000)
                    var resopnse = ByteArray(1024)
                    var readIndex = inputStream.read(resopnse)
                    Log.e("wooran", "readIndex is " + readIndex + " inputstream eqal: " + inputStream);
                }
            }).start();
        }

        binding.btnRequest.setOnClickListener {
            Log.i("wooran", "on request")
            var jsonObject = JSONObject()
            jsonObject.put("androidId", "hello123456")
            var jsonStr = jsonObject.toString()

        }
    }

    lateinit var remoteSocket: Socket;
    lateinit var inputStream: InputStream;
    lateinit var outputStream: OutputStream;


    private fun getIp() = "139.196.17.31"
        //intToIp((applicationContext.getSystemService(WIFI_SERVICE) as WifiManager).connectionInfo.ipAddress)

    private fun intToIp(ip: Int) =
        "${(ip and 0xFF)}.${(ip shr 8 and 0xFF)}.${(ip shr 16 and 0xFF)}.${(ip shr 24 and 0xFF)}"



    override fun receiveClientMsg(success: Boolean, msg: String) {
        Log.i(TAG, "receiveClientMsg: $msg")
    }

    override fun receiveServerMsg(msg: String) {
        Log.i(TAG, "receiveServerMsg: $msg")
    }

    override fun otherMsg(msg: String) {
        Log.i(TAG, "otherMsg: $msg")
    }
}